package com.ego.member.web;

import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayApiException;
import com.ego.common.constant.MemberConstant;
import com.ego.common.to.member.MemberTo;
import com.ego.common.util.Result;
import com.ego.common.vo.product.CartVo;
import com.ego.member.factory.Oauth2LoginFactory;
import com.ego.member.feign.ProductFeign;
import com.ego.member.oauth2.Oauth2;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @program: ego
 * @description: Oauth2登录——社交登录
 * @author: KamTang
 * @create: 2022-12-15 14:00
 **/
@Controller
public class Oauth2Controller {

    @Autowired
    private ProductFeign productFeign;

    @GetMapping("/oauth2.0/{mode}/success")
    public String oauth2(@PathVariable("mode") String mode, HttpServletRequest request, HttpSession session) throws AlipayApiException {
        MemberConstant.LoginMode loginModeEnum = MemberConstant.LoginMode.getEnumByValue(mode);
        // 获取用户选择的社交登录模式
        Oauth2 oauth2 = Oauth2LoginFactory.getLoginMode(loginModeEnum);
        // 根据具体的社交软件执行对应的登录方法
        MemberTo member = oauth2.oauth2Login(request);
        if (ObjectUtils.isNotEmpty(member)) {
            Integer goodNumInCart = 0;
            Result productFeignResp = productFeign.getCurrentUserCartItem(member.getId());
            List<CartVo.CartItem> cartItems = productFeignResp.getData("cartItems", new TypeReference<List<CartVo.CartItem>>() {
            });
            for (CartVo.CartItem cartItem : cartItems) {
                goodNumInCart += cartItem.getCount();
            }
            goodNumInCart += (Integer) session.getAttribute("goodNumInCart");
            member.setGoodNumInCart(goodNumInCart);
            // 由于需要将实体对象存储在远程Redis中，所以会出现序列化问题，需要让对象支持序列化。
            session.setAttribute(MemberConstant.LOGGED_USER, member);
            return "redirect:http://egomall.shop:8006/";
        } else {
            return "redirect:http://egomall.shop:8006/login";
        }
    }


}
